package LoginSystem;

import EncapsulatingObjects.Trip;
import EncapsulatingObjects.User;
import TextDocument.UserAgreement;
import Util.*;
import Weclome.Welcome;

import javax.swing.*;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import java.time.LocalDate;

public class LoginPage {

    JFrame jf;
    JLabel account;
    JLabel password;
    JLabel code;
    Captcha vfcd;

    JTextField taccount;
    JTextField tverificationCode;
    JPasswordField tpass;
    JButton login;
    JLabel register;
    JLabel forgetPassword;
    JRadioButton agreement;
    JLabel agreeText;

    User user = new User();
    String vc;
    UserDatabaseUtil du = new UserDatabaseUtil();
    UiUtil ui = new UiUtil();

    public LoginPage() {
        init();
        ui.setFrameImage(jf);
        ui.setFrameCenter(jf);
        ui.setLogo(jf);
        jf.setVisible(true);
        initUserData();
        initTripData();
        initCart();
    }

    private void init() {
        jf = new JFrame("Login");
        jf.setLayout(null);
        jf.getContentPane().setBackground(Color.white);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setResizable(false);

        account = new JLabel("ACCOUNT");
        taccount = new JTextField(20);
        taccount.setFont(new Font("Times New Roman", Font.BOLD, 20));
        taccount.setBackground(new Color(255, 229, 138, 255));
        taccount.setToolTipText("Please enter you account");
        taccount.setPreferredSize(new Dimension(150, 28));
        MatteBorder border = new MatteBorder(0, 0, 2, 0, new Color(17, 191, 191, 255));
        taccount.setBorder(border);
        taccount.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                user.setAccount(taccount.getText().trim());
                user.setPassword(String.valueOf(tpass.getPassword()).trim());
                vc = tverificationCode.getText().trim();
                if (e.getKeyChar() == '\n') {
                    if (user.getPassword().equals(""))
                        tpass.requestFocus();
                    else {
                        if (vc.equals(""))
                            tverificationCode.requestFocus();
                        else
                            loginClicked();
                    }
                }
            }
        });
        jf.add(account);
        jf.add(taccount);

        password = new JLabel("PASSWORD");
        tpass = new JPasswordField(20);
        tpass.setBackground(new Color(255, 229, 138, 255));
        tpass.setToolTipText("Please enter your password!");
        tpass.setPreferredSize(new Dimension(150, 28));
        tpass.setBorder(border);
        tpass.setFont(new Font("Times New Roman", Font.BOLD, 35));
        tpass.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                user.setAccount(taccount.getText().trim());
                user.setPassword(String.valueOf(tpass.getPassword()).trim());
                vc = tverificationCode.getText().trim();
                if (e.getKeyChar() == '\n') {
                    if (vc.equals(""))
                        tverificationCode.requestFocus();
                    else
                        loginClicked();
                }
            }
        });
        jf.add(password);
        jf.add(tpass);

        vfcd = new Captcha();
        vfcd.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

        code = new JLabel("CAPTCHA");
        jf.add(code);
        tverificationCode = new JTextField(20);
        tverificationCode.setBackground(new Color(255, 229, 138, 255));
        tverificationCode.setPreferredSize(new Dimension(150, 28));
        tverificationCode.setBorder(border);
        tverificationCode.setFont(new Font("Times New Roman", Font.BOLD, 20));
        tverificationCode.setToolTipText("Please enter the verification code on the right.");
        tverificationCode.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == '\n') {
                    loginClicked();
                }
            }
        });
        jf.add(tverificationCode);
        jf.add(vfcd);

        login = new JButton("LOGIN");
        login.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        login.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                loginClicked();
            }
        });
        jf.add(login);

        register = new JLabel("REGISTER");
        register.setForeground(Color.GRAY);
        register.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        register.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                registerClicked(e);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                register.setForeground(Color.BLUE);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                register.setForeground(Color.gray);
            }
        });
        jf.add(register);

        forgetPassword = new JLabel("FORGET PASSWORD");
        forgetPassword.setForeground(Color.GRAY);
        forgetPassword.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        forgetPassword.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                forgetPasswordClicked(e);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                forgetPassword.setForeground(Color.BLUE);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                forgetPassword.setForeground(Color.gray);
            }
        });
        jf.add(forgetPassword);

        agreement = new JRadioButton("Agree");
        agreement.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == '\n') {
                    loginClicked();
                }
            }
        });
        agreement.setBackground(Color.white);
        agreement.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        agreeText = new JLabel("User agreement");
        agreeText.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                UserAgreement.isHelp = false;
                new UserAgreement();
            }
        });
        agreeText.setOpaque(true);
        agreeText.setBackground(Color.white);
        agreeText.setForeground(Color.blue);
        agreeText.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        jf.add(agreement);
        jf.add(agreeText);

        jf.setSize(440, 430);
        account.setBounds(55, 80, 70, 30);
        taccount.setBounds(150, 80, 220, 30);
        password.setBounds(55, 140, 70, 30);
        tpass.setBounds(150, 140, 220, 30);
        code.setBounds(55, 200, 100, 30);
        tverificationCode.setBounds(150, 200, 120, 30);
        vfcd.setBounds(275, 195, 60, 40);
        login.setBounds(70, 260, 290, 50);
        forgetPassword.setBounds(280, 340, 130, 30);
        register.setBounds(30, 340, 70, 30);
        agreement.setBounds(150, 360, 60, 30);
        agreeText.setBounds(210, 365, 96, 20);
    }

    private void registerClicked(MouseEvent e) {
        goResigter();
    }

    private void forgetPasswordClicked(MouseEvent e) {
        goRetrievePassword();
    }

    private void loginClicked() {
        if (!agreement.isSelected()) {
            JOptionPane.showMessageDialog(jf, "Please agree to the user agreement first");
            return;
        }
        int count = 0;
        try {
            user.setAccount(taccount.getText().trim());
            user.setPassword(String.valueOf(tpass.getPassword()).trim());
            vc = tverificationCode.getText().trim();

            if (user.getAccount().equals("") || user.getPassword().equals("") || vc.equals("")) {
                JOptionPane.showMessageDialog(jf, "Please enter all information");
                vfcd.nextCode();
                return;
            }

            if (!vc.equals(vfcd.getCode())) {
                JOptionPane.showMessageDialog(jf, "Please enter the right verification code");
                vfcd.nextCode();
                return;
            }

            if (!Inspectionrules.checkAccount(jf, user.getAccount()) || !Inspectionrules.checkPass(jf, user.getPassword())) {
                return;
            }

            Connection conn = du.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("select * from userdata");

            while (rs.next()) {
                if (user.getAccount().equals(rs.getString("account"))) {
                    if (user.getPassword().equals(rs.getString("password"))) {//getInt(int 第几列/列名)
                        du.updateLoginStatue(user, true);
                        goWelcome();
                        return;
                    } else {
                        JOptionPane.showMessageDialog(jf, "Please enter right password");
                        vfcd.nextCode();
                        return;
                    }
                }
                count++;
            }
            stmt.close();
            if (count == 1) {
                JOptionPane.showMessageDialog(jf, "Please register an account or login with an administrator account!");
                vfcd.nextCode();
                return;
            }
            JOptionPane.showMessageDialog(jf, "Login failed！ Please check account！");
            vfcd.nextCode();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    private void goResigter() {
        jf.dispose();
        new RegisterPage();
    }

    private void goWelcome() {
        jf.dispose();
        new Welcome();
    }

    private void goRetrievePassword() {
        jf.dispose();
        new RetrievePassword();
    }

    private void initUserData() {
        try {
            UserDatabaseUtil ud = new UserDatabaseUtil();
            Connection conn = ud.getConnection();
            ud.createTable(conn);
            User admin = new User(1, "HAPPYER", "123456", "Eric", "15212345678", LocalDate.parse("2001-02-04"), "Male", "Even out of reach, there are ideas that you want to touch");
            ud.insertInfo(conn, admin, true, false);
            conn.close();
        } catch (SQLException ex) {
        } catch (ClassNotFoundException ex) {
        }
    }

    private void initTripData() {
        TripDatabaseUtil td = new TripDatabaseUtil();

        try {
            td.createTable();

            Trip tripa = new Trip(477, "Two days tour of Xi'an Ancient City",
                    "YingChuan", "Xi‘an",
                    Date.valueOf("2020-12-1"),
                    Date.valueOf("2020-12-3"),
                    "Stay in the senior room of Xi'an Hotel, " +
                            "which is located in the South Gate Square of the ancient city of Xi'an." +
                            " Welcome fruit plate is presented and live in peace of mind in case of epidemic situation. " +
                            "Epidemic prevention masks are given to each room", "City Celebrity Hotel");

            Trip tripb = new Trip(646, "Two days  tour to GuBei Shui town",
                    "YingChuan", "BeiJing",
                    Date.valueOf("2020-12-3"),
                    Date.valueOf("2020-12-5"),
                    "he designated scenic spot has its own characteristic Inn accommodation, " +
                            "unlimited battery cars, multiple bus locations, " +
                            "safe travel, and can upgrade Simatai Great Wall / rowing boat", "Xinqiao Hotel");

            Trip trip1 = new Trip(477, "Two days tour of Xi'an Ancient City",
                    "YingChuan", "Xi‘an",
                    Date.valueOf("2020-12-1"),
                    Date.valueOf("2020-12-3"),
                    "Stay in the senior room of Xi'an Hotel, " +
                            "which is located in the South Gate Square of the ancient city of Xi'an." +
                            " Welcome fruit plate is presented and live in peace of mind in case of epidemic situation. " +
                            "Epidemic prevention masks are given to each room", "City Celebrity Hotel");

            Trip trip2 = new Trip(646, "Two days  tour to GuBei Shui town",
                    "YingChuan", "BeiJing",
                    Date.valueOf("2020-12-3"),
                    Date.valueOf("2020-12-5"),
                    "he designated scenic spot has its own characteristic Inn accommodation, " +
                            "unlimited battery cars, multiple bus locations, " +
                            "safe travel, and can upgrade Simatai Great Wall / rowing boat", "Xinqiao Hotel");

            Trip trip3 = new Trip(1442, "Four days tour of Shanghai Suzhou Hangzhou Wuzhen",
                    "ShangHai", "Hangzhou",
                    Date.valueOf("2020-12-3"),
                    Date.valueOf("2020-12-7"),
                    "You can enjoy the three 5A water towns with a gift value of 150 yuan." +
                            "which is located in the South Gate Square of the ancient city of Xi'an." +
                            " You can enjoy the performances of Zhouzhuang Inn and Songcheng theme hotel" +
                            "with a limited number of promotions", "Wanyi Hotel  ");
            Trip trip4 = new Trip(2000, "3-6 days  tour in Beijing",
                    "BeiJing", "BeiJing",
                    Date.valueOf("2020-12-6"),
                    Date.valueOf("2020-12-12"),
                    "Tiananmen and Wangfujing are about 50 meters  " +
                            "away from Dengshikou station of Metro Line 5, " +
                            "with convenient transportation", "Shu Xin Yuan Hotel ");

            Trip trip5 = new Trip(345, "One day car tour to the Western movie city of ZhenBeiBao, Ningxia",
                    "NingXia", "NingXia",
                    Date.valueOf("2020-12-11"),
                    Date.valueOf("2020-12-12"),
                    "Lazy sleep 8:00 departure, hotel pick-up and drop off," +
                            "small group of less than 6 people, one day tour two scenes, " +
                            " easy pure play, 2 people book", "Mansion Hotel");

            Trip trip6 = new Trip(1587, "HaiNan Sanya 5-Day Tour",
                    "YingChuan", "HaiNan",
                    Date.valueOf("2020-12-15"),
                    Date.valueOf("2020-12-20"),
                    "Play without shopping, Atlantis can play as you please.  " +
                            "You can stay at the C-bit hotel of Dadonghai (Mingshen / Weijing / Haman)," +
                            "punch Wuzhizhou Island / Forest Park / ends of the earth / tourist mecca, big and small caves (local tour)",
                    "Meiju Hotel");

            Trip trip7 = new Trip(3900, "Nature Museum ",
                    "Harbin", "Mohe",
                    Date.valueOf("2020-12-20"),
                    Date.valueOf("2020-12-30"),
                    "Looking for the Galactic Aurora Borealis + net red play," +
                            " splashing water into ice + two countries, " +
                            "overlooking the Russian village + Takka extreme north post",
                    "Chinese Arctic Village Hotel");

            Trip trip8 = new Trip(6900, "Cross country self driving",
                    "Chengdu", "Lasa",
                    Date.valueOf("2020-12-6"),
                    Date.valueOf("2020-12-17"),
                    "Cross country self driving · 318 Sichuan Tibet line 11 day tour, " +
                            "guided by Toyota Prado, 4 people and 1 car, Chengdu to Lhasa, Tibet,  " +
                            "accompanied by UAVs, guaranteed by oxygen generator in hotel, and staying in quality hotel",
                    "Renqing Inn  Hotel");

            Trip trip9 = new Trip(6900, " Polar exploration",
                    "Reykjavik", "Blue lake",
                    Date.valueOf("2021-1-20"),
                    Date.valueOf("2021-2-20"),
                    "Polar exploration · Iceland 9 days · small group of 4 people, exclusive car guide,  " +
                            "stay in the blue Lake Hotel + beautiful house in the wilderness, enjoy the hot spring,  " +
                            " meet the gorgeous Aurora, and meet a cute pony for an aurora feast! ",
                    "Beautiful hotel");

            Trip trip10 = new Trip(10699, "Global outdoor",
                    "Oslo", "Copenhagen",
                    Date.valueOf("2021-4-30"),
                    Date.valueOf("2021-5-20"),
                    "Global outdoor · Norway + Denmark for 12 days, a small group of 6 people, " +
                            "exclusive car guide, stay in the fjord Seaview Hotel + classic Manor Hotel, mountain view train  " +
                            " + the road of spirit + the road of Atlantic Ocean, enjoy the beautiful fjord scenery!",
                    "Clarion Hotel Admiral Bergen");

            Trip trip11 = new Trip(5600, "Maldives Pisces island 5 days free travel",
                    "Maldives", "Maldives",
                    Date.valueOf("2021-7-5"),
                    Date.valueOf("2021-7-10"),
                    "Olhuveli Beach & Spa is located in Kaafu Atoll, South male, with 129 rooms on the island." +
                            "which is located in the South Gate Square of the ancient city of Xi'an." +
                            " Olhuveli Beach & Spa is located in Kaafu Atoll, South male, with 129 rooms on the island." +
                            "Spa hall adopts five elements aromatherapy of traditional Chinese medicine.",
                    "Sun Siyam Olhuveli Maldives");

            Trip trip12 = new Trip(2900, "9 days in Italy",
                    "Italy", "Italy",
                    Date.valueOf("2020-12-10"),
                    Date.valueOf("2020-12-19"),
                    "A small group of 6 people, exclusive car guide, Chateau wine taster + historian explain, " +
                            "stay in manor villa + Lakeside Garden Hotel + classical monastery Hotel, " +
                            "our famous cities of Rome + Florence + Venice + Milan, meet the unexpected scenery!",
                    "Lakeside Garden Hotel");

            Trip trip13 = new Trip(206, "One day tour in Tengger Desert, Shapotou",
                    "Zhongwei", "Tengger Desert ",
                    Date.valueOf("2020-12-16"),
                    Date.valueOf("2020-12-17"),
                    "Deep into the hinterland of Tengger Desert,  " +
                            "12 people are comfortable without shopping group, and 1 person orders every day. " +
                            "They are given desert magic scarf and enjoy delicious Chinese food",
                    "Royal post Hotel");

            Trip trip14 = new Trip(2184, "Chengdu Jiuzhaigou Dujiangyan 6-day Tour",
                    "Ningxia", "Chengdu",
                    Date.valueOf("2020-12-15"),
                    Date.valueOf("2020-12-21"),
                    "Land air bus, 5-year benchmarking line," +
                            "which is located in the South Gate Square of the ancient city of Xi'an." +
                            " 5-night high-end accommodation, clock in scenic spots along the way, " +
                            "24h pick-up, post epidemic security", " Renqing Hotel");

            Trip trip15 = new Trip(2908, "Guangzhou Zhuhai Shuangfei 5-Day Tour ",
                    "GanSu", "Guangzhou",
                    Date.valueOf("2020-12-20"),
                    Date.valueOf("2020-12-25"),
                    "Enjoy Changlong double garden, ocean Kingdom fireworks show," +
                            "close contact with rare animals, view the Hong Kong Zhuhai Macao Bridge," +
                            "the whole high-end accommodation", "LanYin Hotel");

            Trip trip16 = new Trip(699, "Two days  tour to GuBei Shui town",
                    "BeiJing", "BeiJing",
                    Date.valueOf("2020-12-3"),
                    Date.valueOf("2020-12-5"),
                    "Shuizhen hotel is a hot spring at the foot of the Great Wall." +
                            "You can buy a night tour of the Great Wall at the foot of the Great Wall, a cold water fish feast," +
                            " and the Great Wall music and water dance show on Wangjing street",
                    "Sofitel Hotel");

            Trip trip17 = new Trip(2134, "7-day tour to Meidong",
                    "BeiJing", "NewYork",
                    Date.valueOf("2020-12-22"),
                    Date.valueOf("2020-12-29"),
                    "Free access to Capitol, New York, Philadelphia, " +
                            "Washington, D.C., Corning, Niagara Falls, Boston, Harvard University",
                    "Ramada Hotel");

            Trip trip18 = new Trip(1827, "Shanghai Disneyland Hotel 4 days visit ",
                    "YingChuan", "ShangHai",
                    Date.valueOf("2020-12-23"),
                    Date.valueOf("2020-12-27"),
                    "Stay in the Disneyland Resort, Toy Story / Disneyland Hotel are optional. " +
                            " You can buy tickets to Disneyland and enjoy the fairytale kingdom",
                    " MaoChengXuan Hotel ");

            Trip trip19 = new Trip(9199, "Gansu Gannan 4-member private group for 7 days",
                    "YingChuan", "GanSu",
                    Date.valueOf("2020-12-16"),
                    Date.valueOf("2020-12-23"),
                    "Walking on the human fairyland zhagana, the land of miracles Ganjia secret land," +
                            "crossing Sangke grassland, guomang wetland visiting Labrang temple," +
                            " Langmu Temple + nine storey demon tower of Daka", " ZhengPing Hotel");

            Trip trip20 = new Trip(4699, "7-day cross-country tour of Xinjiang Ring Road",
                    "GanSu", "XinJiang",
                    Date.valueOf("2020-12-15"),
                    Date.valueOf("2020-12-22"),
                    "no shopping / Kanas / World devil city / Hemu village / passionate skiing / snow hot spring / ice drift / strict accommodation",
                    "RuiYuan Hotel");

            td.insertInfo(tripa);
            td.insertInfo(tripb);
            td.insertInfo(trip1);
            td.insertInfo(trip2);
            td.insertInfo(trip3);
            td.insertInfo(trip4);
            td.insertInfo(trip5);
            td.insertInfo(trip6);
            td.insertInfo(trip7);
            td.insertInfo(trip8);
            td.insertInfo(trip9);
            td.insertInfo(trip10);
            td.insertInfo(trip11);
            td.insertInfo(trip12);
            td.insertInfo(trip13);
            td.insertInfo(trip14);
            td.insertInfo(trip15);
            td.insertInfo(trip16);
            td.insertInfo(trip17);
            td.insertInfo(trip18);
            td.insertInfo(trip19);
            td.insertInfo(trip20);
        } catch (Exception e) {
        }
    }

    private void initCart() {
        ShoppingCartUtil su = new ShoppingCartUtil();
        try {
            su.createTable();
            su.initTrips();
        } catch (SQLException throwables) {
        }
    }

    public static void main(String[] args) {
        new LoginPage();
    }
}
